package com.ncmmall.application.business.setting;

import com.ncmmall.domain.business.setting.SystemSetting;
import com.ncmmall.domain.business.setting.SystemSettingRecord;
import com.ncmmall.domain.business.setting.SystemSettingRecordRepository;
import com.ncmmall.domain.business.setting.SystemSettingRepository;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.querychannel.service.QueryChannelService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.Collections;

/**
 * @author likaikai
 * @description 系统设置
 * @date 2019-07-06 14:33:52
 */
@Service
@Transactional
public class SystemSettingApplication {

    private static final Logger log = LoggerFactory.getLogger(SystemSettingApplication.class);

    @Autowired
    private SystemSettingRepository systemSettingRepository;

    @Autowired
    private SystemSettingRecordRepository systemSettingRecordRepository;

    @Autowired
    private QueryChannelService queryChannelService;


    /**
     * 修改系统设置
     *
     * @param systemSetting
     * @param type
     */
    public void modify(SystemSetting params, int type, WebUser user) {
        SystemSetting setting = queryChannelService.queryOneEntity("select * from mall_system_setting limit 1", Collections.emptyMap(), SystemSetting.class);
        if (setting == null) {
            setting = new SystemSetting();
        }
        switch (type) {

            case SystemSetting.INVOICE:
                setting.setInvoiceTitle(params.getInvoiceTitle());
                setting.setInvoiceNumber(params.getInvoiceNumber());
                setting.setInvoiceScale(params.getInvoiceScale());
                setting.setSupplierInvoiceScale(params.getSupplierInvoiceScale());
                setting.setInvoiceAddress(params.getInvoiceAddress());
                break;

            case SystemSetting.MEMBER_PROTOCOL:
                setting.setRegisterProtocol(params.getRegisterProtocol());
                break;
            case SystemSetting.MERCHANT_ENTER_PROTOCOL:
                setting.setMerchantEnterProtocol(params.getMerchantEnterProtocol());
                break;
            default:
                break;
        }
        systemSettingRepository.save(setting);

        SystemSettingRecord record = new SystemSettingRecord();
        record.setType(type);
        record.setWebUser(user);
        record.setCreateTime(new Timestamp(System.currentTimeMillis()));
        BeanUtils.copyProperties(params, record);
        systemSettingRecordRepository.save(record);
    }


    public void modify(SystemSetting setting) {
        systemSettingRepository.save(setting);
    }

}
